package cn.zhentao.service.impl;

import cn.zhentao.mapper.DeliveryTasksMapper;
import cn.zhentao.mapper.OrdersMapper;
import cn.zhentao.mapper.VTaskPackageOrdersMapper;
import cn.zhentao.pojo.DeliveryTasks;
import cn.zhentao.pojo.Orders;
import cn.zhentao.pojo.VTaskPackageOrders;
import cn.zhentao.service.IDeliveryTasksService;
import cn.zhentao.vo.QueryPage;
import cn.zhentao.vo.TaskDetailsVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 配送任务表 服务实现类
 * </p>
 *
 * @author mp
 * @since 2025-06-16
 */
@Service
public class DeliveryTasksServiceImpl extends ServiceImpl<DeliveryTasksMapper, DeliveryTasks> implements IDeliveryTasksService {
    // Mybatis-Plus 会自动注入 delivery_tasks 表的 baseMapper
    @Autowired
    private DeliveryTasksMapper deliveryTasksMapper;

    // 注入我们新创建的、用于查询视图的 Mapper
    @Autowired
    private VTaskPackageOrdersMapper vTaskPackageOrdersMapper;


    @Override
    public List<TaskDetailsVo> findAllTask(QueryPage queryPage) {
        List<TaskDetailsVo> list = deliveryTasksMapper.findAllTask(queryPage);
        return list;
    }

    @Override
    public List<TaskDetailsVo> findAllTaskGroup(QueryPage queryPage) {
        List<TaskDetailsVo> list = deliveryTasksMapper.findAllTaskGroup(queryPage);
        return list;
    }



    // **新增**: 注入 Orders 表的 Mapper
    @Autowired
    private OrdersMapper ordersMapper;

    /**
     * 配送员接受任务包 (最终完美版)
     */
    @Override
    @Transactional // 保证两个更新操作要么都成功，要么都失败
    public boolean acceptTask(String packageId, String deliverymanId) {
        List<Long> orderIds = vTaskPackageOrdersMapper.selectOrderIdsByPackageId(packageId);

        if (orderIds == null || orderIds.isEmpty()) {
            return false;
        }

        // --- 核心逻辑：确保任务记录存在 ---
        QueryWrapper<DeliveryTasks> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("order_id", orderIds);
        // **修正点1：直接用 this.list() 代替 deliveryTasksMapper.selectList()**
        List<DeliveryTasks> existingTasks = this.list(queryWrapper);

        List<Long> existingOrderIds = existingTasks.stream()
                .map(DeliveryTasks::getOrderId) // 现在类型都是 Long，不会报错
                .collect(Collectors.toList());

        List<Long> missingOrderIds = new ArrayList<>(orderIds);
        missingOrderIds.removeAll(existingOrderIds);

        if (!missingOrderIds.isEmpty()) {
            List<DeliveryTasks> newTasksToInsert = new ArrayList<>();
            for (Long missingId : missingOrderIds) {
                DeliveryTasks newTask = new DeliveryTasks();
                newTask.setOrderId(missingId); // 类型匹配，不会报错
                newTask.setStatus(0);
                newTask.setCreatedAt(LocalDateTime.now());
                newTasksToInsert.add(newTask);
            }
            // **修正点2：使用 Service 层提供的 saveBatch 方法**
            this.saveBatch(newTasksToInsert);
        }

        // --- 更新逻辑 ---
        UpdateWrapper<DeliveryTasks> taskUpdateWrapper = new UpdateWrapper<>();
        taskUpdateWrapper
                .set("status", 2)
                .set("deliveryman_id", deliverymanId)
                .set("start_time", LocalDateTime.now())
                .in("order_id", orderIds)
                .eq("status", 0);

        // **修正点3：直接用 this.update() 代替 deliveryTasksMapper.update()**
        int rowsAffectedInTasks = this.baseMapper.update(null, taskUpdateWrapper);
        // 或者用 boolean result = this.update(taskUpdateWrapper);

        if (rowsAffectedInTasks != orderIds.size()) {
            throw new RuntimeException("任务包中的部分订单已被他人接受，接单失败，数据已回滚。");
        }

        UpdateWrapper<Orders> orderUpdateWrapper = new UpdateWrapper<>();
        orderUpdateWrapper.set("status", 2).in("id", orderIds);
        ordersMapper.update(null, orderUpdateWrapper);

        return true;
    }
    @Override
    public boolean cancelTaskPackage(String packageId) {
        // 1. 查找该任务包下所有订单ID
        List<VTaskPackageOrders> vOrders = vTaskPackageOrdersMapper.selectList(
                new QueryWrapper<VTaskPackageOrders>().eq("package_id", packageId)
        );
        if (vOrders.isEmpty()) return false;
        List<Long> orderIds = vOrders.stream().map(VTaskPackageOrders::getOrderId).collect(Collectors.toList());

        // 2. 批量更新 orders 表
        Orders update = new Orders();
        update.setStatus(0); // 0=待配送
        int updated = ordersMapper.update(
                update,
                new QueryWrapper<Orders>()
                        .in("id", orderIds)
                        .eq("status", 2) // 只改配送中的
        );

        // 3. 同步更新 DeliveryTasks 表
        DeliveryTasks taskUpdate = new DeliveryTasks();
        taskUpdate.setStatus(0); // 0=待接单/待配送
        int updatedTasks = deliveryTasksMapper.update(
                taskUpdate,
                new QueryWrapper<DeliveryTasks>()
                        .in("order_id", orderIds)
                        .eq("status", 2) // 只改配送中的
        );

        // 只要有一张表有更新就算成功
        return updated > 0 || updatedTasks > 0;
    }

    @Override
    @Transactional
    public boolean collectPackageAndOrders(String packageId) {
        // 1. 更新任务包表


        // 2. 找到该任务包下所有订单ID
        List<VTaskPackageOrders> vOrders = vTaskPackageOrdersMapper.selectList(
                new QueryWrapper<VTaskPackageOrders>().eq("package_id", packageId)
        );
        if (vOrders.isEmpty()) return false;
        List<Long> orderIds = vOrders.stream().map(VTaskPackageOrders::getOrderId).collect(Collectors.toList());
        int updatedPackage = deliveryTasksMapper.update(
                null,
                new UpdateWrapper<DeliveryTasks>()
                        .in("order_id", orderIds)
                        .set("is_collected", 1)
        );
        // 3. 更新订单表
        int updatedOrders = ordersMapper.update(
                null,
                new UpdateWrapper<Orders>()
                        .in("id", orderIds)
                        .set("is_collected", 1)

        );

        return updatedPackage > 0 && updatedOrders > 0;
    }

    @Override
    public List<VTaskPackageOrders> getUncollectedPackagesByDeliveryman(Integer deliverymanId) {
        // 1. 先查出所有有未揽收订单的 package_id
        List<String> packageIds = vTaskPackageOrdersMapper.selectDistinctPackageIdsWithUncollectedOrders(deliverymanId);

        // 2. 再查任务包详情
        if (packageIds.isEmpty()) return Collections.emptyList();
        return vTaskPackageOrdersMapper.selectList(
                new QueryWrapper<VTaskPackageOrders>().in("package_id", packageIds)
        );
    }






}
